package payment;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Payment;

/**
 * 請求ボタンを押したときの処理
 * 未処理の請求データを請求済みに変える
 * @author matsumoto
 *
 */
public class CashServlet extends HttpServlet 
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		req.setCharacterEncoding("UTF-8");
		String msg = null;
		//未処理の請求データを取得
		List<Payment> list = Payment.find_not_yet();
		if(list.size() != 0 && list != null)
		{
			int count = 0;
			for(int i=0;i<list.size();i++)
			{
				Payment p = list.get(i);
				boolean b = credit(p);
				if(b){
					p.setPaid();
					count++;
				}
			}
			msg = list.size() + "件中" + count + "件請求しました。";
		}
		else
		{
			msg = "未処理の請求データはありません。";
		}
		req.setAttribute("msg", msg);
		RequestDispatcher dispatcher = req.getRequestDispatcher("../operator/cashManage.jsp");
		dispatcher.forward(req, resp);
	}
	/**
	 * 決済依頼を出すメソッド
	 * @param p
	 * @return	決済結果
	 */
	private boolean credit(Payment p){
		final String URL_PAYMENT = "http://localhost:8080/Payment/Payment"; 
		//決済を依頼する URL 
		boolean credit = false;
		try{
			URL url = new URL(URL_PAYMENT); 
			//決済代行業者のシステムに接続する 
			HttpURLConnection connection = null; 
			connection = (HttpURLConnection) url.openConnection(); 
			//POST メソッドで送信する 
			connection.setRequestMethod("POST"); 
			connection.setDoOutput(true); 
			//パラメータを設定 
			// number : クレジットカード番号 
			// amount : 金額 
			// account : アカウント 
			// password : パスワード 
			StringBuffer param = new StringBuffer(); 
			param.append("number=" + p.getCard()); 
			param.append("&amount=" + (p.getPrice_total()+p.getFee())); 
			param.append("&account=iten7"); 
			param.append("&password=hZ5A82iN"); 
			//パラメータを送信する 
			PrintWriter printWriter = new PrintWriter(connection.getOutputStream()); 
			printWriter.print(param.toString()); 
			printWriter.close(); 
			//結果を取得する 
			switch (connection.getResponseCode()) { 
			case HttpURLConnection.HTTP_OK: 
			 //決済完了 
				credit = true;
			 break; 
			case HttpURLConnection.HTTP_ACCEPTED: 
			 //決済できなかった（与信額不足など） 
			 break; 
			case HttpURLConnection.HTTP_BAD_REQUEST: 
			 //パラメータが間違っている 
			 break; 
			} 
		}
		catch(IOException e){
			e.printStackTrace();
		}
		return credit;
	}
}
